<template>
  <div class="stores_next_cate">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item"><span class="search-label">输入搜索：</span><Input placeholder="分类编码/分类名称"
                 v-model='name'></Input></Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="seleted">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item"><Button class="search-btn"
                  type="primary"
                  @click="add"
                  v-if="hasPermission('moms:scs:productcategorycreate')"
                  style="margin-right:8px">添加分类</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe
           class="table-list"
           :columns="columns"
           :data="tableData"
           :height="tableHeight"
           :loading="loading">
      <template slot-scope="{ row }"
        slot="level">
        <span>二级</span>
      </template>
      <template slot-scope="{ row }"
        slot="isShow">
        <span>{{ getEnumsName(row.isShow, categoryShow) }}</span>
      </template>
      <template slot-scope="{ row }"
        slot="setting">
        <div class="btn-text-group">
          <span class="btn-text" @click="lookBefore(row)">查看上级</span>
          <span class="btn-text" @click="openModel(row)">转移商品</span>
        </div>
      </template>
      <template slot-scope="{ row }"
        slot="action">
        <!-- <i class="iconsys icondetail"
          @click="skipDetail(row)"
          v-if="hasPermission('moms:scs:productcategorydetail')"
           title="查看"></i> -->
        <i class="iconsys iconedit"
          @click="skipEdit(row)"
          v-if="hasPermission('moms:scs:productcategoryupdate')"
          title="编辑"></i>
        <Poptip confirm title="你确定要删除吗？" @on-ok="sureDel(row)"
          v-if="hasPermission('moms:scs:productcategorydelete')"
          style="text-align:left">
          <i class="iconsys icondel" title="删除" ></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex'
         justify="end"
         style='padding: 20px'>
      <Col>
      <Page :total="pageObj.total"
            :page-size='pageObj.pageSize'
            :current='pageObj.pageIndex'
            :page-size-opts='[10,20,50,100]'
            show-total
            show-sizer
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <Modal v-model="modalShow"
           width="480"
           title="转移商品"
           :closable='false'>
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="110"
            style="margin:20px 0 0 15px">
        <FormItem label="原商品分类："
                  prop="prevClassify">
          <Input placeholder="原商品分类"
                 v-model='formValidate.prevClassify'
                 disabled
                 style="width:200px"></Input>
        </FormItem>
        <FormItem label="目标商品分类："
                  prop="targetClassify">
          <Select v-model="formValidate.targetClassify" style="width: 200px">
            <Option v-for="(item, index) in targetClassifyList" :value="item.sysCategoryId" :key="index" :disabled="item.sysCategoryId === selectRow.sysCategoryId">{{ item.categoryName }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button style="width:78px;margin-right:10px"
                @click='cancel'>取消</Button>
        <Button type="primary"
                style="width:78px"
                @click="startTransfer">开始转移</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import enumsMixin from './enums'
import { getCategoryList, deleteCategory, transferCategory, getOrgTag } from '@/api/purchase/index.js'
export default {
  name: 'stores_next_cate',
  mixins: [enumsMixin],
  data () {
    return {
      id: '',
      name: '',
      loading: false,
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      tableHeight: 0,
      modalShow: false,
      tableData: [],
      formValidate: {
        prevClassify: '',
        targetClassify: ''
      },
      selectRow: {},
      ruleValidate: {
        targetClassify: {
          validator: (rule, value, callback) => {
            if (!this.formValidate.targetClassify) {
              callback(new Error('请选择目标商品分类'))
            } else {
              callback()
            }
          }
        }
      },
      targetClassifyList: [],
      columns: [
        {
          title: '分类编码',
          key: 'sysCategoryId'
        },
        {
          title: '分类名称',
          key: 'categoryName'
        },
        {
          title: '级别',
          slot: 'level'
        },
        {
          title: '商品数量',
          key: 'goodsCount'
        },
        {
          title: '是否显示',
          slot: 'isShow'
        },
        {
          title: '设置',
          slot: 'setting',
          width: 400
        }
      ],
      orgTagList: []
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.id !== to.query.id) {
        vm.id = to.query.id
        vm.seleted()
      } else {
        vm.getData()
      }
    })
  },
  mounted () {
    this.id = this.$route.query.id
    getOrgTag({
      merchantId: this.$store.state.user.merchantId,
      id: this.$store.state.user.orgId
    }).then(res => {
      if (res.data.status === 200) {
        this.orgTagList = res.data.data
        this.getData()
        this.getAllCategory()
      } else {
        this.$Message.error(`${res.data.error}`)
      }
    })
    if (this.hasPermission(['moms:scs:productcategoryupdate', 'moms:scs:productcategorydelete'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 200
      })
    }
  },
  methods: {
    getData () {
      this.loading = true
      this.tableHeight = 0
      getCategoryList({
        merchantId: this.merchantId,
        keyword: this.name,
        level: 2,
        sortBy: 'ASC',
        parentId: this.$route.query.id,
        offset: (this.pageObj.pageIndex - 1) * this.pageObj.pageSize,
        limit: this.pageObj.pageSize,
        orgTagId: this.orgTagList.map(item => item.id)
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data.categories || []
          this.pageObj.total = result.data.total || 0
          if (this.tableData.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.message}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    getAllCategory () {
      getCategoryList({
        merchantId: this.merchantId,
        sortBy: 'ASC',
        level: 2,
        offset: 0,
        limit: 999999,
        orgTagId: this.orgTagList.map(item => item.id)
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.targetClassifyList = result.data.categories || []
        } else {
          this.$Message.error(`${result.message}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    sureDel (row) {
      deleteCategory({
        merchantId: this.merchantId,
        categoryId: row.sysCategoryId,
        level: 2
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          setTimeout(() => {
            this.getData()
          }, 300)
        } else {
          this.$Message.error(`${result.message}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    seleted () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    lookBefore (row) {
      this.$router.push({
        name: 'stores_cate'
      })
    },
    openModel (row) {
      this.selectRow = row
      this.$refs.formValidate.resetFields()
      this.formValidate.prevClassify = row.categoryName
      this.formValidate.targetClassify = ''
      this.modalShow = true
    },
    cancel () {
      this.modalShow = false
    },
    startTransfer () {
      this.$refs.formValidate.validate(val => {
        if (val) {
          transferCategory({
            merchantId: this.merchantId,
            updater: this.userId,
            updaterName: this.userName,
            sourceCategoryId: this.formValidate.prevClassify,
            targetCategoryId: this.formValidate.targetClassify
          }).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.modalShow = false
              this.$Message.success('转移成功！')
              this.getData()
            } else {
              this.$Message.error(`${result.message}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    reset () {
      this.name = ''
      this.seleted()
    },
    changePageIndex (page) {
      this.pageObj.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.seleted()
    },
    skipEdit (row) {
      this.$router.push({
        name: 'stores_cate_edit',
        query: {
          id: row.sysCategoryId,
          type: '2',
          beforeId: this.id,
          orgTagId: row.orgTagId
        }
      })
    },
    add () {
      this.$router.push({
        name: 'stores_cate_create',
        query: {
          id: this.id,
          type: '2'
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.btn-text-group {
  .btn-text {
    margin-right: 20px;
    color: rgb(45, 140, 240);
    cursor: pointer
  }
}
</style>
